#include "mainwindow.h"

#include "ui_mainwindow.h"

MainWindow::MainWindow(QTcpSocket* sock, QWidget* parent)
    : QMainWindow(parent), ui(new Ui::MainWindow), sock(sock) {
    ui->setupUi(this);
    setWindowIcon(QIcon(":/message-line.png"));

    ui->scrollChatListWidgetContents->layout()->setAlignment(Qt::AlignTop);
    ui->scrollChatMessageWidgetContents->layout()->setAlignment(Qt::AlignBottom);

    connect(sock, SIGNAL(readyRead()), this, SLOT(handRead()));    
}

MainWindow::~MainWindow() { delete ui; }

void MainWindow::handRead() {
    QByteArray recvData = sock->readAll();
    QString recvStr(recvData);
    recvStr1=recvStr.split('#');
    qDebug()<<"recvStr1";
    bool cleared = false;
    for(int i=0;i<recvStr1.size();i++)
    {
        qDebug()<<i;
        recvStrList = recvStr1[i].split('|');
        qDebug()<<recvStrList[0];
        if( recvStrList[0]=="03" )
          {
               if(recvStrList[1]=="0")
               {
                  QMessageBox::information(NULL, "提示","您必须先添加该用户好友才能聊天",
                                                          QMessageBox::Yes);
               }
               for(int i=0;i<chatList.size();i++)
               {   QString friendName = chatList[i]->name;
                   QString recvName = recvStrList[1];
                   if(QString::localeAwareCompare(recvName, friendName)==0)
                   {
                       chatList[i]->messageList.push_back(newMessageFrame(recvStrList[1],recvStrList[2],recvStrList[3]));
                       if(QString::localeAwareCompare(presentFrame->name, friendName) == 0)
                            pushMessage(presentFrame->messageList[presentFrame->messageList.size() - 1]);//判断发送者是否是当前停留界面的好友
                       break;
                   }
               }
            }
        if (recvStrList[0] == "04")
        {
            if (recvStrList[1] == "0")
                QMessageBox::information(NULL, "提示", "ta已经是你的好友了",
                                         QMessageBox::Yes);
            else if (recvStrList[1] == "1")
                QMessageBox::information(NULL, "提示", "你已经发出过申请了",
                                         QMessageBox::Yes);
            else if (recvStrList[1] == "2")
                QMessageBox::information(NULL, "提示", "没有这名用户，请检查用户名",
                                         QMessageBox::Yes);
            else if (recvStrList[1] == "3"){
                QMessageBox::StandardButton result = QMessageBox::information(
                    NULL, "提示", "用户<b>" + recvStrList[2] + "</b>想要加您为好友",
                    QMessageBox::Yes | QMessageBox::No);
                switch (result) {
                    case QMessageBox::Yes: {
                        ChatInfoFrame* f = new ChatInfoFrame(recvStrList[1]);
                        chatList.push_back(f);
                        connect(f, SIGNAL(clicked()), this, SLOT(handClickChat()));
                        ui->scrollChatListWidgetContents->layout()->addWidget(
                            chatList[chatList.size() - 1]);

                        QString registerData =
                            "#05|1|" + recvStrList[2] + "|" + username;
                        registerData.toStdString().c_str();
                        qDebug() << registerData;
                        sock->write(registerData.toUtf8());

                        break;
                    }
                    case QMessageBox::No: {
                        QString registerData =
                            "#05|0|" + recvStrList[2] + "|" + username;
                        registerData.toStdString().c_str();
                        qDebug() << registerData;
                        sock->write(registerData.toUtf8());

                        break;
                    }
                    default:
                        break;
                }
            }
        }
        if(recvStrList[0] == "05")
        {
            if (recvStrList[2] == "0")
                QMessageBox::information(NULL, "提示", "用户<b>" + recvStrList[2] + "</b>已同意加您为好友", QMessageBox::Yes);
            else if (recvStrList[2] == "1")
                QMessageBox::information(NULL, "提示", "用户<b>" + recvStrList[2] + "</b>拒绝了加您为好友", QMessageBox::Yes);
        }
        if (recvStrList[0] == "06")
            {
                if (recvStrList[1] == "0")
                    QMessageBox::information(NULL, "提示", "删除成功",
                                             QMessageBox::Yes);
                else if (recvStrList[1] == "1")
                    QMessageBox::information(NULL, "提示", "删除失败",
                                             QMessageBox::Yes);

            }
        if(recvStrList[0]=="07")
       {
            ChatInfoFrame* f = new ChatInfoFrame(recvStrList[1]);
            chatList.push_back(f);
            ui->scrollChatListWidgetContents->layout()->addWidget(f);
            connect(f, SIGNAL(clicked()), this, SLOT(handClickChat()));
            qDebug()<<recvStrList[2];
            if(recvStrList[2]=="1")
            {
                qDebug()<<"1";
                presentFrame = chatList[chatList.size()-1];
                presentFrame->setOnlineStatus(true);
                presentFrame->setSelectedStatus(true);

                ui->lcdTotalChatNumber->display(++totalChatNumber);
                ui->lcdOnlineChatNumber->display(++onlineChatNUmber);
            }
            if(recvStrList[2]=="0")
            {
                qDebug()<<"0";
                presentFrame = chatList[chatList.size()-1];
                presentFrame->setOnlineStatus(false);
                presentFrame->setSelectedStatus(true);

                ui->lcdTotalChatNumber->display(++totalChatNumber);
            }
       }
        if (recvStrList[0] == "08")
        {
                if(recvStrList[1]=="0")
                {
                   QMessageBox::information(NULL, "提示","被查询用户不存在",
                                                           QMessageBox::Yes);
                }
                else if(recvStrList[1]=="1")
                {
                    clearPresentMessage();
                    if(!cleared){
                        presentFrame->messageList.clear();
                        cleared = true;
                    }

                    presentFrame->messageList.push_back(
                        newMessageFrame(recvStrList[2], recvStrList[4], recvStrList[5]));
                    showPresentMessage();
                }
         }
    }
}

void MainWindow::handClickChat() {
    QString clickedName = ((ChatInfoFrame*)sender())->name;
    if (clickedName == presentFrame->name) return;

    //清空然后重新绘制聊天信息
    clearPresentMessage();
    presentFrame->setSelectedStatus(false);
    for (unsigned int i = 0; i < chatList.size(); i++)
        if (clickedName == chatList[i]->name) presentFrame = chatList[i];
    presentFrame->setSelectedStatus(true);
    showPresentMessage();
}

void MainWindow::getData(QString str) { username = str; }

void MainWindow::on_buttonSendMessage_clicked() {
    QString data = ui->editSendMessage->toPlainText();
    if (data != "") {
        ui->editSendMessage->setText("");
        QString recName = presentFrame->name;
        QString uName = username;
        QDateTime current_date_time = QDateTime::currentDateTime();
        QString current_date =
            current_date_time.toString("yyyy-MM-dd hh:mm:ss");
        presentFrame->messageList.push_back(
            newMessageFrame(uName, current_date, data));
        pushMessage(
            presentFrame->messageList[presentFrame->messageList.size() - 1]);
        QString sendData = "#03|" + uName + "|" + recName + "|" + data;
        sendData.toStdString().c_str();
        qDebug() << sendData;
        sock->write(sendData.toUtf8());
    }
}

void MainWindow::on_actionAddFriend_triggered() {
    bool isOK;
    QString text = QInputDialog::getText(NULL, "添加好友", "用户名",
                                         QLineEdit::Normal, "", &isOK);
    if (isOK && text == "")
        QMessageBox::information(NULL, "提示", "请输入目标用户名",
                                 QMessageBox::Yes);
    if (isOK && text != "") {
        QMessageBox::information(NULL, "提示",
                                 "已向用户 <b>" + text + "</b> 发送好友请求",
                                 QMessageBox::Yes);
    }
    QString uName = username;
    QString sendData = "#04|" + uName + "|" + text;
    sendData.toStdString().c_str();
    qDebug() << sendData;
    sock->write(sendData.toUtf8());
}

QFrame* MainWindow::newMessageFrame(QString name, QString dateTime,
                                    QString message) {
    QFrame* messageFrame = new QFrame;
    messageFrame->setLayout(new QVBoxLayout);
    QLabel* senderLabel = new QLabel;
    QLabel* messageLabel = new QLabel;

    extern QFont ft;
    senderLabel->setFont(ft);
    messageLabel->setFont(ft);
    messageLabel->setTextInteractionFlags(Qt::TextSelectableByMouse);
    messageLabel->setWordWrap(true);
    messageLabel->setCursor(Qt::IBeamCursor);

    senderLabel->setText(name + "(" + dateTime + "):");
    messageLabel->setText(message);

    messageFrame->layout()->addWidget(senderLabel);
    messageFrame->layout()->addWidget(messageLabel);
    return messageFrame;
}

void MainWindow::pushMessage(QFrame* messageFrame) {
    ui->scrollChatMessageWidgetContents->layout()->addWidget(messageFrame);
    //立即处理addWidget触发的QResizeEvent，否则滚动条无法移动到底部
    QCoreApplication::processEvents();
    //有两个才能正确运行，我也不知道为什么
    QCoreApplication::processEvents();
    ui->scrollChatMessage->verticalScrollBar()->setValue(__INT_MAX__);
}

void MainWindow::receiveMessage(QString name, QString dateTime,
                                QString message) {
    QFrame* messageFrame = newMessageFrame(name, dateTime, message);
    //插入过去的聊天中
    for (unsigned int i = 0; i < chatList.size(); i++) {
        if (name == chatList[i]->name) {
            chatList[i]->messageList.push_back(messageFrame);
            chatList[i]->setLatestMessage(message);
            if (chatList[i] == presentFrame)
                pushMessage(messageFrame);
            else
                chatList[i]->setMessageMarked(true);
            return;
        }
    }
    //打开新的聊天，清空然后重新绘制聊天列表
    for (unsigned int i = 0; i < chatList.size(); i++)
        chatList[i]->setParent(NULL);
    ChatInfoFrame* f = new ChatInfoFrame(name);
    chatList.push_back(f);
    ui->scrollChatListWidgetContents->layout()->addWidget(f);
    f->messageList.push_back(messageFrame);
    f->setLatestMessage(message);
    connect(f, SIGNAL(clicked()), this, SLOT(handClickChat()));
    ui->lcdTotalChatNumber->display(++totalChatNumber);
    ui->lcdOnlineChatNumber->display(++onlineChatNUmber);
    for (unsigned int i = 0; i < chatList.size(); i++)
        ui->scrollChatListWidgetContents->layout()->addWidget(chatList[i]);
}

void MainWindow::clearPresentMessage() {
    if(presentFrame == NULL)return;
    for (unsigned int i = 0; i < presentFrame->messageList.size(); i++)
        presentFrame->messageList[i]->setParent(NULL);
}
void MainWindow::showPresentMessage() {
    if(presentFrame == NULL)return;
    for (unsigned int i = 0; i < presentFrame->messageList.size(); i++)
        pushMessage(presentFrame->messageList[i]);
}

void MainWindow::on_actionDeleteFriend_triggered() {
    if (chatList.size() == 1) {
        QMessageBox::information(NULL, "提示", "您至少要有一个好友",
                                 QMessageBox::Yes);
        return;
    }
    bool isOK;
    QString text = QInputDialog::getText(NULL, "删除好友", "用户名",
                                         QLineEdit::Normal, "", &isOK);
    if (text == "") {
        QMessageBox::information(NULL, "提示", "请输入目标用户名",
                                 QMessageBox::Yes);
        return;
    }
    for (unsigned int i = 0; i < chatList.size(); i++) {
        //判断当前界面
        if (QString::localeAwareCompare(text, chatList[i]->name) == 0) {
            if (QString::localeAwareCompare(presentFrame->name,
                                            chatList[i]->name) == 0) {
                QMessageBox::information(NULL, "提示",
                                         "请切换到其他好友界面再删除该好友",
                                         QMessageBox::Yes);
                return;
            }

            //发送删除信息
            QString uName = username;
            QString delName = chatList[i]->name;
            QString sendDelData = "#06|" + uName + "|" + delName;
            sendDelData.toStdString().c_str();
            qDebug() << sendDelData;
            sock->write(sendDelData.toUtf8());

            //删除好友列表中的好友
            ui->scrollChatListWidgetContents->layout()->removeWidget(
                chatList[i]);
            delete chatList[i];
            chatList.erase(chatList.begin() + i);
            QMessageBox::information(
                NULL, "提示", "已将用户 <b>" + text + "</b> 从列表中删除",
                QMessageBox::Yes);
            return;
        }
    }
    QMessageBox::information(NULL, "提示", "没有此用户", QMessageBox::Yes);
}

void MainWindow::on_actionRefreshOnlineState_triggered() {
    QString sendData = "#07|" + username;
    sendData.toStdString().c_str();
    qDebug() << sendData;
    sock->write(sendData.toUtf8());
    for(int i=0;i<chatList.size();i++)
    {
        chatList[i]->setParent(NULL);
        clearPresentMessage();
    }
    totalChatNumber=0;
    onlineChatNUmber=0;
    ui->lcdTotalChatNumber->display(totalChatNumber);
    ui->lcdOnlineChatNumber->display(onlineChatNUmber);
}

void MainWindow::on_actionAbout_triggered() {
    QMessageBox::about(
        NULL, "关于",
        "<b>WebChat</b>"
        "<p>一款简单的即时通信软件，基于Qt开发，使用了Remix Icon</p>"
        "<a "
        "href=\'https://gitee.com/destroy314/web-chat'>https://gitee.com/"
        "destroy314/web-chat</a>");
}

void MainWindow::on_actionRefreshChat_triggered() {
    //向服务器发送获取历史消息的请求
    QString friendName = presentFrame->name;
    QString uName = username;
    QString sendData = "#08|" + uName + "|" + friendName;
    sendData.toStdString().c_str();
    qDebug() << sendData;
    sock->write(sendData.toUtf8());
}
